package gitee.derumin.lib_for_derumin.commands.suggestionproviders;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.suggestion.SuggestionProvider;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import gitee.derumin.lib_for_derumin.helpers.config.ConfigHelper;
import net.minecraft.server.command.ServerCommandSource;

import java.util.concurrent.CompletableFuture;

public class ConfigElementSuggestionProvider implements SuggestionProvider<ServerCommandSource> {
    public static final ConfigElementSuggestionProvider PROVIDER = new ConfigElementSuggestionProvider();
    @Override
    public CompletableFuture<Suggestions> getSuggestions(CommandContext<ServerCommandSource> context, SuggestionsBuilder builder) throws CommandSyntaxException {
        JsonObject object1 = null;
        String[] nodes = context.getInput().split(" ");
        for (int i = nodes.length - 3; i > -1; i--){
            if (nodes[i].equals("modify") || nodes[i].equals("get") || nodes[i].equals("reset")){
                object1 = ConfigHelper.getConfigByName(nodes[i+1], false);
                if (object1 != null && object1.has(nodes[i+2])){
                    JsonElement element1 = object1.get(nodes[i+2]);
                    String  contains1;
                    try {
                        contains1 = element1.getAsString();
                    }catch (Exception e){
                        contains1 = element1.toString();
                    }
                    builder.suggest("(current:)" + contains1);
                    JsonObject object2 = ConfigHelper.getDefaultConfigJson(nodes[i+1]);
                    if (object2 != null && object2.has(nodes[i+2])){
                        JsonElement element2 = object2.get(nodes[i+2]);
                        String  contains2;
                        try {
                            contains2 = element2.getAsString();
                        }catch (Exception e){
                            contains2 = element2.toString();
                        }
                        builder.suggest("(default:)" + contains2);
                    }
                }
                break;
            }
        }
        if (object1 == null){
            builder.suggest("no such config");
        }
        return builder.buildFuture();
    }
}
